<template>
  <div class="booking-management-page">
    <h2>预订管理</h2>
    
    <!-- 筛选区域 -->
    <el-card class="filter-section">
      <div class="filter-form">
        <el-form :inline="true" :model="filterForm">
          <el-form-item label="订单状态">
            <el-select v-model="filterForm.paymentStatus" placeholder="选择订单状态">
              <el-option label="全部" value="" />
              <el-option label="已预约" :value="0" />
              <el-option label="已支付" :value="1" />
              <el-option label="已退款" :value="2" />
              <el-option label="已失效" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="order-list-section" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <el-button type="primary" @click="refreshOrders">刷新</el-button>
        </div>
      </template>

      <el-empty v-if="orders.length === 0" description="暂无订单数据" />

      <el-table v-else :data="filteredOrders" style="width: 100%">
        <el-table-column prop="orderId" label="订单ID" width="100">
          <template #default="{ row }">
            {{ row.orderId || row.order_id }}
          </template>
        </el-table-column>
        <el-table-column prop="roomName" label="会议室" width="120">
          <template #default="{ row }">
            {{ row.roomName || row.room_name }}
          </template>
        </el-table-column>
        <el-table-column label="预订时间" width="300">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime || row.start_time) }} 至 {{ formatDateTime(row.endTime || row.end_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalFee" label="金额" width="100">
          <template #default="{ row }">
            ¥{{ row.totalFee || row.total_fee }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusType(row.paymentStatus || row.payment_status)">
              {{ getPaymentStatusText(row.paymentStatus || row.payment_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="showOrderDetails(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          background
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="订单详情"
      width="500px"
    >
      <div v-if="selectedOrder" class="order-details">
        <p><strong>订单ID：</strong>{{ selectedOrder.orderId || selectedOrder.order_id }}</p>
        <p><strong>会议室：</strong>{{ selectedOrder.roomName || selectedOrder.room_name }}</p>
        <p><strong>开始时间：</strong>{{ formatDateTime(selectedOrder.startTime || selectedOrder.start_time) }}</p>
        <p><strong>结束时间：</strong>{{ formatDateTime(selectedOrder.endTime || selectedOrder.end_time) }}</p>
        <p><strong>订单金额：</strong>¥{{ selectedOrder.totalFee || selectedOrder.total_fee }}</p>
        <p><strong>订单状态：</strong>{{ getPaymentStatusText(selectedOrder.paymentStatus || selectedOrder.payment_status) }}</p>
        <p v-if="selectedOrder.cancelTime || selectedOrder.cancel_time">
          <strong>取消时间：</strong>{{ formatDateTime(selectedOrder.cancelTime || selectedOrder.cancel_time) }}
        </p>
        <p v-if="selectedOrder.refundFee || selectedOrder.refund_fee">
          <strong>退款金额：</strong>¥{{ selectedOrder.refundFee || selectedOrder.refund_fee }}
        </p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getAllOrders, getOrdersByPage, pageByCondition } from '@/apis/orders'

// 状态管理
const loading = ref(false)
const orders = ref([])
const selectedOrder = ref(null)
const detailsDialogVisible = ref(false)
const userStore = useUserStore()
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = ref({
  paymentStatus: '',
  dateRange: []
})

// 获取所有订单 - 使用分页条件查询
const fetchOrders = async () => {
  loading.value = true
  try {
    // 构建查询条件 - 使用Orders对象格式，与后端对应
    const queryParams = new Object()
    
    // 根据筛选条件构建查询参数
    if (filterForm.value.paymentStatus !== '') {
      queryParams.paymentStatus = parseInt(filterForm.value.paymentStatus)
    }
    
    // 如果有日期范围，添加到查询条件
    if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
      queryParams.startTime = filterForm.value.dateRange[0] + ' 00:00:00'
      queryParams.endTime = filterForm.value.dateRange[1] + ' 23:59:59'
    }
    
    console.log('请求参数:', {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      queryParams
    })
    
    // 调用后端分页条件查询接口
    const { code, data, msg } = await pageByCondition(
      pagination.value.pageNum,
      pagination.value.pageSize,
      queryParams
    )
    
    console.log('响应数据:', { code, data, msg })
    
    if (code === 200 && data) {
      // 检查返回数据结构
      if (data.records) {
        orders.value = data.records
        pagination.value.total = data.total || 0
      } else if (Array.isArray(data)) {
        // 如果直接返回数组
        orders.value = data
        pagination.value.total = data.length
      } else {
        // 如果是其他格式，尝试适配
        orders.value = data.list || data.content || []
        pagination.value.total = data.total || data.totalElements || 0
      }
      
      if (orders.value.length === 0 && pagination.value.total > 0 && pagination.value.pageNum > 1) {
        // 如果当前页没有数据，但总数不为0，说明可能是最后一页被删空了
        // 自动跳转到前一页
        pagination.value.pageNum -= 1
        fetchOrders()
      }
    } else {
      ElMessage.error(msg || '获取订单列表失败')
      orders.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败: ' + (error.message || error))
    orders.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 筛选订单 - 直接使用后端筛选
const filteredOrders = computed(() => {
  return orders.value
})

// 处理筛选
const handleFilter = () => {
  pagination.value.pageNum = 1 // 重置到第一页
  fetchOrders()
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    paymentStatus: '',
    dateRange: []
  }
  pagination.value.pageNum = 1 // 重置到第一页
  fetchOrders()
}

// 刷新订单列表
const refreshOrders = () => {
  fetchOrders()
}

// 显示订单详情
const showOrderDetails = (order) => {
  selectedOrder.value = order
  detailsDialogVisible.value = true
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取支付状态文本
const getPaymentStatusText = (status) => {
  switch (status) {
    case 0: return '已预约'
    case 1: return '已支付'
    case 2: return '已退款'
    case 3: return '已失效'
    default: return '未知'
  }
}

// 获取支付状态类型
const getPaymentStatusType = (status) => {
  switch (status) {
    case 0: return 'info'     // 蓝色
    case 1: return 'success'  // 绿色
    case 2: return 'warning'  // 黄色
    case 3: return 'danger'   // 红色
    default: return 'info'
  }
}

// 处理页码变化
const handlePageChange = (newPage) => {
  pagination.value.pageNum = newPage
  fetchOrders()
}

// 处理每页显示数量变化
const handleSizeChange = (newSize) => {
  pagination.value.pageSize = newSize
  pagination.value.pageNum = 1 // 重置到第一页
  fetchOrders()
}

// 监听分页参数变化，自动重新获取数据
watch(
  () => [pagination.value.pageNum, pagination.value.pageSize],
  () => {
    fetchOrders()
  },
  { immediate: false }
)

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.booking-management-page {
  padding: 2rem;
}

.filter-section {
  margin-bottom: 2rem;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-list-section {
  margin-bottom: 2rem;
}

.order-details {
  padding: 1rem;
}

.order-details p {
  margin: 0.5rem 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-tag) {
  text-align: center;
  min-width: 60px;
}
</style> 